package com.example.demo.service;

import com.example.demo.mapper.OrderMapper;
import com.example.demo.mapper.ExpressMapper;
import com.example.demo.model.OrderInfo;
import com.example.demo.model.ExpressInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Random;

@Service
public class OrderService implements OrderMapper {
    
    private static final Logger log = LoggerFactory.getLogger(OrderService.class);

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ExpressMapper expressMapper;

    // 实现OrderMapper接口的方法
    @Override
    public int createOrder(OrderInfo orderInfo) {
        return orderMapper.createOrder(orderInfo);
    }

    @Override
    public List<OrderInfo> getBoughtOrders(Integer userId, String status) {
        return orderMapper.getBoughtOrders(userId, status);
    }

    @Override
    public List<OrderInfo> getSoldOrders(Integer userId, String status) {
        return orderMapper.getSoldOrders(userId, status);
    }

    @Override
    public OrderInfo getOrderByOrderNo(String orderNo) {
        return orderMapper.getOrderByOrderNo(orderNo);
    }

    @Override
    public int updateOrderStatus(OrderInfo orderInfo) {
        return orderMapper.updateOrderStatus(orderInfo);
    }

    @Override
    public int updateOrderDelete(OrderInfo order) {
        return orderMapper.updateOrderDelete(order);
    }

    // 业务方法
    @Transactional
    public OrderInfo createOrderWithDetails(OrderInfo orderInfo) {
        try {

            
            // 设置订单状态为待付款
            orderInfo.setStatus("待付款");
            
            // 设置创建时间
            orderInfo.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .format(new Date()));
            
            // 生成订单号
            String orderNo = "DD" + new SimpleDateFormat("yyMMddHHmmss").format(new Date())
                    + String.format("%03d", new Random().nextInt(1000));
            orderInfo.setOrderNo(orderNo);
            
            // 初始化删除标记
            orderInfo.setBuyerDelete(0);
            orderInfo.setSellerDelete(0);
            
            // 创建订单
            int result = createOrder(orderInfo);
            if (result <= 0) {
                throw new RuntimeException("创建订单失败");
            }
            
            return orderInfo;
        } catch (Exception e) {
            log.error("创建订单失败", e);
            throw new RuntimeException("创建订单失败: " + e.getMessage());
        }
    }

    @Transactional
    public boolean confirmReceive(String orderNo, Integer userId) {
        OrderInfo order = getOrderByOrderNo(orderNo);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }
        order.setStatus("已收货");
        return updateOrderStatus(order) > 0;
    }

    @Transactional
    public boolean ship(ExpressInfo expressInfo, Integer sellerId) {
        try {
            OrderInfo order = getOrderByOrderNo(expressInfo.getOrderNo());
            if (order == null || !order.getSellerId().equals(sellerId)) {
                return false;
            }

            expressInfo.setSendTime(new Date());
            expressMapper.insert(expressInfo);

            order.setStatus("待收货");
            order.setExpressNo(expressInfo.getExpressNo());
            return updateOrderStatus(order) > 0;
        } catch (Exception e) {
            log.error("发货失败", e);
            throw e;
        }
    }

    @Transactional
    public boolean cancelOrder(String orderNo, Integer userId, String reason, boolean isSeller) {
        OrderInfo order = getOrderByOrderNo(orderNo);
        if (order == null || !"待付款".equals(order.getStatus())) {
            return false;
        }
        
        if (isSeller && !order.getSellerId().equals(userId)) {
            return false;
        }
        if (!isSeller && !order.getBuyerId().equals(userId)) {
            return false;
        }
        
        order.setStatus("已取消");
        order.setRemark(reason);
        return updateOrderStatus(order) > 0;
    }

    @Transactional
    public boolean deleteOrder(String orderNo, Integer userId, boolean isSeller) {
        OrderInfo order = getOrderByOrderNo(orderNo);
        if (order == null) {
            return false;
        }
        
        if (isSeller && !order.getSellerId().equals(userId)) {
            return false;
        }
        if (!isSeller && !order.getBuyerId().equals(userId)) {
            return false;
        }
        
        if (isSeller) {
            order.setSellerDelete(1);
        } else {
            order.setBuyerDelete(1);
        }
        
        return updateOrderDelete(order) > 0;
    }
}
